import * as api from '../../api/common';

Page({
  data: {
    nickName: ''
  },

  onLoad: function (options) {
    const userInfo = tt.getStorageSync('info');
    if (userInfo && userInfo.nickname) {
      this.setData({
        nickName: userInfo.nickname
      });
    }
  },

  inputNickName(e) {
    this.setData({
      nickName: e.detail.value
    });
  },

  async updateNickName() {
    const newNickName = this.data.nickName.trim();
    if (!newNickName) {
      tt.showToast({
        title: '请输入昵称',
        icon: 'none'
      });
      return;
    }

    try {
      const userInfo = tt.getStorageSync('info');
      const response = await api.updateUserInfo({
        id: userInfo.id,
        nickname: newNickName
      });

      if (response.code === 0) {
        tt.showToast({
          title: response.msg || '昵称更新失败',
          icon: 'none'
        });
      } else {
        tt.showToast({
          title: '昵称更新成功',
          icon: 'success'
        });

        // 更新本地存储中的用户信息
        userInfo.nickname = newNickName;
        tt.setStorageSync('info', userInfo);

        tt.navigateBack(); // 返回上一页
      }
    } catch (error) {
      tt.showToast({
        title: '昵称更新失败',
        icon: 'none'
      });
      console.error('昵称更新失败：', error);
    }
  }
});
